package com.ruoyi.session;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.commons.codec.binary.Hex;
import org.springframework.stereotype.Component;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;

@Component
public class DeviceManager {
    private final ConcurrentHashMap<String, DeviceSession> devices = new ConcurrentHashMap<>();
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public void addDevice(String deviceKey, ChannelHandlerContext ctx) {
        DeviceSession session = new DeviceSession(deviceKey, ctx);
        devices.put(deviceKey, session);
        System.out.println("设备连接: " + deviceKey);
    }

    public void removeDevice(String deviceKey) {
        DeviceSession session = devices.remove(deviceKey);
        if (session != null) {
            System.out.println("移除掉线设备: " + deviceKey);
            session.close();
        }
    }

    public boolean sendCommand(String deviceKey, byte[] command) {
        DeviceSession session = devices.get(deviceKey);
        if (session != null && session.isActive()) {
            session.getCtx().writeAndFlush(Unpooled.copiedBuffer(command));
            System.out.println("发送指令 " + deviceKey + ": " + Hex.encodeHexString(command));
            return true;
        }
        return false;
    }

    // 也可以定时打印在线设备
    public void startCleanupTask() {
        scheduler.scheduleAtFixedRate(() -> {
            devices.forEach((deviceKey, session) -> {
                if (!session.isActive()) {
                    System.out.println("清除离线设备: " + deviceKey);
                    removeDevice(deviceKey);
                }
            });
        }, 5, 5, TimeUnit.SECONDS); // 每5秒检查一次
    }

    public void shutdown() {
        scheduler.shutdown();
    }
}
